package club.dmyang.controller;

import club.dmyang.common.enums.RespCodeEnums;
import club.dmyang.common.vo.CategoryVo;
import club.dmyang.common.vo.ResposeVo;
import club.dmyang.common.vo.TagVo;
import club.dmyang.entity.Category;
import club.dmyang.entity.Tag;
import club.dmyang.service.ArticleService;
import club.dmyang.service.CategoryService;
import club.dmyang.service.TagService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by brss on 2018/7/25.
 */
@Controller
@RequestMapping("/tag")
public class TagController {

    @Autowired
    private TagService tagService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/listAll")
    @ResponseBody
    public ResposeVo listAll(){
        try {
            //从缓存中读
            String categoryListall = redisTemplate.opsForValue().get("tag_listall");
            if ( categoryListall != null ){
                ResposeVo resposeVo = JSON.parseObject(categoryListall, ResposeVo.class);
                return resposeVo;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //无法读缓存时也不能影响正常业务
        }
        //返回给模版的List
        List<TagVo> tagVoList = new ArrayList<>();
        List<Tag> tagList = tagService.findAll();
        for (Tag t : tagList) {
            //查询某标签下的文章个数
            Integer num = articleService.findNumByTagId(t.getTid());
            TagVo tagVo = new TagVo();
            tagVo.setTid(t.getTid());
            tagVo.setTname(t.getTname());
            tagVo.setNum(num);
            tagVoList.add(tagVo);
        }
        //返回的数据对象
        ResposeVo resposeVo = new ResposeVo(RespCodeEnums.RESP_CODE_SUCC.getCode(), "查询成功！", 0, tagVoList);
        //对象转json
        String resposeVoJson = JSON.toJSONString(resposeVo);
        try {
            //写缓存
            redisTemplate.opsForValue().set("tag_listall",resposeVoJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //因为不需要分页，所以传回count无意义，故传0
        return resposeVo;
    }

}
